package com.sfd.test.config;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.sleuth.instrument.async.LazyTraceExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.concurrent.Executor;

/**
 * 线程执行器配置
 * @author haden
 * @date 2022/12/2 17:11
 **/
@Configuration
@EnableAutoConfiguration
@EnableAsync
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class AsyncThreadExecutorConfig implements AsyncConfigurer {

    @Resource
    private BeanFactory beanFactory;

    @Override
    @Bean("asyncExecutorWithTrace")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setMaxPoolSize(32);
        executor.setCorePoolSize(16);
        executor.setQueueCapacity(1000);
        executor.setThreadNamePrefix("AsyncThread-trace-");
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60 * 30);
        executor.setDaemon(false);
        executor.initialize();
        return new LazyTraceExecutor(this.beanFactory, executor);
    }

}